package cn.abcsys.cloud.devops.web.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

//import cn.abcsys.cloud.devops.web.entity.Authority;
import cn.abcsys.cloud.devops.web.entity.User;
//import cn.abcsys.cloud.devops.web.util.RequestUtil;
/**
 * 访问拦截器
 * 
 * @author mingwei.dmw
 *
 */
@Repository
public class AccessInterceptor implements HandlerInterceptor {
	private static final Logger LOGGER = Logger.getLogger(AccessInterceptor.class);
	private List<String> ignores;
	private List<String> ignoreUrls;
	//private Map<String, Authority> dictionary;
	/**
	 * @return the ignores
	 */
	public List<String> getIgnores() {
		return ignores;
	}
	/**
	 * @param ignores the ignores to set
	 */
	public void setIgnores(List<String> ignores) {
		this.ignores = ignores;
	}

	public void setIgnoreUrls(List<String> ignoreUrls) {
		this.ignoreUrls = ignoreUrls;
	}

	public List<String> getIgnoreUrls() {
		return ignoreUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String requestPath = request.getServletPath();
        request.setCharacterEncoding("UTF-8");
		if (null != ignores) {
			for (String url : ignores) {
				if (requestPath.contains(url)) {
					return true;
				}
			}
		}
		User user = (User) request.getSession().getAttribute("user");
		if (null == user) {
			LOGGER.warn("该url已被拦截：" + requestPath);
			Map<String,Integer> result = new HashMap<String,Integer>();
			//返回302状态码，跳转首页
			result.put("status", 302);
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().println(JSONObject.toJSONString(result));
			response.flushBuffer();
			/*Result result = new Result(false, "越权访问！");
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().println(JSONObject.toJSONString(result));
			response.flushBuffer();*/
			response.getWriter().close();
			return false;
		} else {
			if (null != ignoreUrls) {
				for (String url : ignoreUrls) {
					if (requestPath.contains(url)) {
						return true;
					}
				}
			}
			/*@SuppressWarnings("unchecked")
			List<String> authlist = (List<String>) request.getSession().getAttribute("authlist");
			if (!requestPath.equals("/")) {
				if (!authlist.contains(requestPath.replaceAll("/\\d+", ""))) {
					LOGGER.warn("该url已被拦截：" + requestPath);
					Result result = new Result(false, "越权访问！");
					response.setContentType("application/json;charset=utf-8");
					response.getWriter().println(JSONObject.toJSONString(result));
					response.flushBuffer();
					response.getWriter().close();
					return false;
				}
			}*/
			
			/*String accessIp = RequestUtil.getRemoteHost(request);
			Enumeration<String> params = request.getParameterNames();
			StringBuffer requestContent = new StringBuffer();
			if (null != params) {
				while (params.hasMoreElements()) {
					String param = params.nextElement();
					String value = request.getParameter(param);
					requestContent.append(param).append(":").append(value).append("|");
				}
			}
			if (requestPath.isEmpty() || requestPath.equals("/")) {
			} else {
				String actionUrl = requestPath.split("/")[1];
				if (dictionary.containsKey(actionUrl)) {
					Authority authority= (Authority) dictionary.get(requestPath.split("/")[1]);
					actionUrl = authority.getAuthorityRelativeUrl();
				}
				if (dictionary.containsKey(requestPath)) {
					Authority authority= (Authority) dictionary.get(requestPath);
					TimeZone.setDefault(TimeZone.getTimeZone("Etc/GMT-8"));
					request.setAttribute("accessLog", actionUrl);
				}
			}*/
			return true;
		}
		
		/*
		String requestPath = request.getServletPath();
		String type = request.getHeader("X-Requested-With");// XMLHttpRequest
		LOGGER.info("url=========>>"+requestPath);
		 //String regEx1 = "[a-zA-z]+://[^\\s]*\\.(html|js|ico|json|png|css)$";//匹配url .do的操作
		 String regEx = "(monitor|role|area|clusterEnv|permissions|env|user|runtime|containerManger|application|instrument)";
		//匹配这几种含有url的字符串 
		 Pattern pattern = Pattern.compile(regEx);
		 Matcher matcher = pattern.matcher(requestPath);
		 boolean rs = matcher.find();//是否存在
		 //String regEx ="[^\\s]*\\.(do|)$";
		 // 编译正则表达式
		if(rs){
			User user = (User) request.getSession().getAttribute("user");
			if (null == user) {
				// 重定向
				String path = request.getContextPath();
				String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
				// 转发
				if (StringUtils.equals("XMLHttpRequest", type)) {
					//ajax请求 
					response.setHeader("SESSIONSTATUS", "TIMEOUT");
					response.setHeader("CONTEXTPATH", basePath+"index.jsp");
					response.setStatus(HttpServletResponse.SC_FORBIDDEN);
					//request.getRequestDispatcher("/index.jsp").forward(request, response);
					LOGGER.info("ajax类型的会话失效=========>>跳转");
					return false;
				} else {
					LOGGER.info("普通请求的类型的会话失效=========>>跳转");
					//response.sendRedirect(basePath);
					Map<String,Integer> result = new HashMap<String,Integer>();
					//返回302状态码，跳转首页
					result.put("status", 302);
					Result result = new Result(false, "会话失效！");
					response.setContentType("application/json;charset=utf-8");
					response.getWriter().println(JSONObject.toJSONString(result));
					response.flushBuffer();
					response.getWriter().close();
					request.getSession().invalidate();
					//response.sendRedirect(basePath);
					return false;
				}
			} 
		}
		return true;
	*/}
	
//  request.setCharacterEncoding("UTF-8");
//	if (null != ignores) {
//		for (String url : ignores) {
//			if (requestPath.contains(url)) {
//				return true;
//			}
//		}
//	}
//			@SuppressWarnings("unchecked")
//			List<String> authlist = (List<String>) request.getSession().getAttribute("authlist");
//			if (!requestPath.equals("/")) {
//				if (!authlist.contains(requestPath.replaceAll("/\\d+", ""))) {
//					logger.warn("该url已被拦截：" + requestPath);
//					Result result = new Result(false, "越权访问！");
//					response.setContentType("application/json;charset=utf-8");
//					response.getWriter().println(JSONObject.toJSONString(result));
//					response.flushBuffer();
//					response.getWriter().close();
////					request.getSession().invalidate();
////					response.sendRedirect(request.getContextPath() + "/login.html");
//					return false;
//				}
//			}
//			return true;
//		}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
